import type {
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import axios from "axios";

import appConfig from "@/config";
// import useUserStore from '@/store/userStore';
import { message } from "ant-design-vue";
interface RequestOptions extends AxiosRequestConfig {
  mock?: boolean;
}

// const TOKEN_INVALID = "Token认证失败，请重新登录";
// const NETWORK_ERROR = "网络请求异常，请稍后重试";
const service = axios.create({
  baseURL: appConfig.baseApi,
  timeout: 80000,
});
console.log("appConfig", appConfig.baseApi);

// 请求拦截
service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  console.log("======= 请求参数config =======\n", config);

  //   const headers = config.headers;

  //   const { token } = useUserStore();
  //   if (!headers['Authorization'] && token) {
  //     headers.Authorization = `Bearer ${token}`;
  //   }
  return config;
});

// 响应拦截
service.interceptors.response.use((res: AxiosResponse) => {
  console.log("=======返回数据 res =======\n", res);
  const { status, data, statusText } = res;
  if (status == 200) {
    if (data.code == 200) {
      //   message.success(data.message);

      return data.data;
    } else {
      message.error(data.message);

      return Promise.reject(data.message);
    }
  } else message.error(statusText);
});
/**
 * @description 请求核心函数
 * @param {*} options 请求配置
 *
 */
function request<T>(options: RequestOptions): Promise<T> {
  options.method = options.method?.toLowerCase() || "get";
  if (options.method === "get") {
    options.params = options.data;
  }
  const isMock = options.mock ?? appConfig.mock;

  if (appConfig.env == "production") {
    service.defaults.baseURL = appConfig.baseApi;
  } else {
    service.defaults.baseURL = isMock ? appConfig.mockApi : appConfig.baseApi;
  }
  return service(options) as Promise<T>;
}





// 为request函数添加快捷方法
["get", "post", "put", "delete", "patch"].forEach((method) => {
  (request as any)[method] = (
    url: string,
    data?: any,
    options?: RequestOptions
  ) => {
    return request({ url, data, method, ...options });
  };
});

export default request;
